<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="商家id" prop="businessId">-->
<!--        <el-input-->
<!--            v-model="queryParams.bussinessId"-->
<!--            placeholder="请输入商家id"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺开门时间" prop="shopOpenTime" label-width="150px">
        <el-date-picker clearable
                        v-model="queryParams.shopOpenTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择店铺开门时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="店铺关门时间" prop="shopCloseTime" label-width="150px" >
        <el-date-picker clearable
                        v-model="queryParams.shopCloseTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择店铺关门时间">
        </el-date-picker>
      </el-form-item>

<!--      <el-form-item label="店铺联系电话" prop="shopTel">-->
<!--        <el-input-->
<!--            v-model="queryParams.shopTel"-->
<!--            placeholder="请输入店铺联系电话"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="店铺余额" prop="shopProfit">-->
<!--        <el-input-->
<!--            v-model="queryParams.shopProfit"-->
<!--            placeholder="请输入店铺余额"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="配送费" prop="deliveryFee">-->
<!--        <el-input-->
<!--            v-model="queryParams.deliveryFee"-->
<!--            placeholder="请输入配送费"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="门牌号" prop="roomNo">-->
<!--        <el-input-->
<!--            v-model="queryParams.roomNo"-->
<!--            placeholder="请输入门牌号"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['order:shop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['order:shop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['order:shop:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['order:shop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="门店头像" align="center" prop="shopAvatar" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.shopAvatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="shopName" />
      <!--      <el-table-column label="店铺id，主键自增" align="center" prop="shopId" />-->
      <el-table-column label="联系人姓名" align="center" prop="businessName" />
      <el-table-column label="店铺联系电话" align="center" prop="shopTel" />
      <el-table-column label="详细地址" align="center" prop="shopAddress" />
      <el-table-column label="门牌号" align="center" prop="roomNo" />
      <el-table-column label="店铺是否营业" align="center" width="100px">
        <!-- 使用默认插槽自定义渲染内容 -->
        <template #default="scope">
          <span v-html="formatShopStatus(scope.row.shopStatus)"></span>
        </template>
      </el-table-column>
      <el-table-column label="店铺开始营业时间" align="center" prop="shopOpenTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shopOpenTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺结束营业时间" align="center" prop="shopCloseTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shopCloseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺公告" align="center" prop="shopAnnouncement" />
      <el-table-column label="门店简介" align="center" prop="shopIntroduce" />
      <el-table-column label="店铺的商业类型" align="center" prop="shopType" />
      <el-table-column label="店铺照片" align="center" prop="shopPhoto" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.shopPhoto" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="营业执照" align="center" prop="shopLicense" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.shopLicense" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="店铺余额" align="center" prop="shopProfit" />
      <el-table-column label="配送费" align="center" prop="deliveryFee" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="CircleCheck" @click="openAudit(scope.row)" v-hasPermi="['order:shop:edit']">审核</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:shop:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:shop:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 审核弹窗 -->
    <el-dialog title="门店审核" v-model="auditOpen" width="480px" append-to-body>
      <el-form ref="auditRef" :model="auditForm" :rules="auditRules" label-width="90px">
        <el-form-item label="审核结果" prop="decision">
          <el-radio-group v-model="auditForm.decision">
            <el-radio label="PASS">审核通过</el-radio>
            <el-radio label="REJECT">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="auditForm.decision === 'REJECT'" label="拒绝原因" prop="rejectReason">
          <el-input v-model="auditForm.rejectReason" type="textarea" :rows="3" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditOpen=false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改已入驻商家对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shopRef" :model="form" :rules="rules" >
        <el-form-item label="商家ID" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入商家ID" />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="businessName">
          <el-input v-model="form.businessName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="店铺开门时间" prop="shopOpenTime">
          <el-date-picker clearable
                          v-model="form.shopOpenTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择店铺开门时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺关门时间" prop="shopCloseTime">
          <el-date-picker clearable
                          v-model="form.shopCloseTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择店铺关门时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺公告" prop="shopAnnouncement">
          <el-input v-model="form.shopAnnouncement" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="店铺联系电话" prop="shopTel">
          <el-input v-model="form.shopTel" placeholder="请输入店铺联系电话" />
        </el-form-item>
        <el-form-item label="门店地址" prop="shopAddress">
          <el-input v-model="form.shopAddress" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="门店简介" prop="shopIntroduce">
          <el-input v-model="form.shopIntroduce" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="门店头像" prop="shopAvatar">
          <image-upload v-model="form.shopAvatar"/>
        </el-form-item>
        <el-form-item label="店铺照片" prop="shopPhoto">
          <image-upload v-model="form.shopPhoto"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="shopLicense">
          <image-upload v-model="form.shopLicense"/>
        </el-form-item>
        <!--        <el-form-item label="店铺余额" prop="shopProfit">-->
        <!--          <el-input v-model="form.shopProfit" placeholder="请输入店铺余额" />-->
        <!--        </el-form-item>-->
        <el-form-item label="配送费" prop="deliveryFee">
          <el-input v-model="form.deliveryFee" placeholder="请输入配送费" />
        </el-form-item>
        <el-form-item label="门牌号" prop="roomNo">
          <el-input v-model="form.roomNo" placeholder="请输入门牌号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shop">
import { listShop, getShop, delShop, addShop, updateShop} from "@/api/order/shop"
import {getBusiness} from "@/api/order/business"


const { proxy } = getCurrentInstance()

const shopList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: null,
    businessName: null,
    shopStatus: null,
    shopOpenTime: null,
    shopCloseTime: null,
    shopAnnouncement: null,
    shopName: null,
    shopTel: null,
    shopAddress: null,
    shopIntroduce: null,
    shopType: null,
    shopAvatar: null,
    shopPhoto: null,
    shopLicense: null,
    shopProfit: null,
    deliveryFee: null,
    roomNo: null
  },
  rules: {
    businessId: [
      { required: true, message: "商家ID不能为空", trigger: "blur" }
    ],
    businessName: [
      { required: true, message: "联系人姓名不能为空", trigger: "blur" }
    ],
    shopStatus: [
      { required: true, message: "店铺状态不能为空", trigger: "change" }
    ],
    shopOpenTime: [
      { required: true, message: "店铺开门时间不能为空", trigger: "blur" }
    ],
    shopCloseTime: [
      { required: true, message: "店铺关门时间不能为空", trigger: "blur" }
    ],
    shopName: [
      { required: true, message: "店铺名称不能为空", trigger: "blur" }
    ],
    shopTel: [
      { required: true, message: "店铺联系电话不能为空", trigger: "blur" }
    ],
    shopAddress: [
      { required: true, message: "门店地址不能为空", trigger: "blur" }
    ],
    shopType: [
      { required: true, message: "店铺的商业类型不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
/** 查询已入驻商家列表 */
function getList() {
  loading.value = true
  listShop(queryParams.value).then(async response => {
    // 1. 获取原始店铺列表
    const initialShopList = response.rows
    // console.log(response.rows)
    total.value = response.total
    console.log(initialShopList)
    // 2. 为每条店铺数据添加联系人姓名
    const settledMerchantsList = await Promise.all(
        initialShopList.map(async (shop) => {
          // console.log(shop)
          try {
            // 调用接口获取商家信息（包含联系人姓名）
            const businessInfo = await getBusiness(shop.businessId)
            //console.log(businessInfo.data.businessName)
            // 返回合并后的数据（原店铺信息 + 联系人姓名）
            return {
              ...shop,
              businessName: businessInfo.data.businessName || '未知联系人'
            }
          } catch (error) {
            console.error(`获取商家${shop.businessId}信息失败:`, error)
            // 即使获取失败也保留原始店铺信息，避免整条数据丢失
            return {
              ...shop,
              businessName: '获取失败'
            }
          }
        })
    )
    // 3. 更新店铺列表
    // 仅显示状态为 3（审核中） 和 4（审核不通过）
    const filtered = settledMerchantsList.filter(s => Number(s.shopStatus) === 3 || Number(s.shopStatus) === 4)
    shopList.value = filtered
    // 若需要让分页总数与过滤后数量一致，可同步重置 total
    total.value = filtered.length
    loading.value = false
     console.log(shopList.value)
  }).catch(error => {
    console.error('查询店铺列表失败:', error)
    loading.value = false
  })
}

// 格式化店铺营业状态（Element Plus 适配版）
const formatShopStatus = (status) => {
  const statusMap = {
    1: { text: '正常营业',   textColor: '#10b981', bgColor: '#dcfce7' },
    2: { text: '暂停营业',   textColor: '#ef4444', bgColor: '#fee2e2' },
    3: { text: '审核中',     textColor: '#f59e0b', bgColor: '#fef3c7' },
    4: { text: '审核不通过', textColor: '#dc2626', bgColor: '#fee2e2' }
  }
  const c = statusMap[status] || { text: `未知状态(${status})`, textColor: '#6b7280', bgColor: '#f3f4f6' }
  return `<span style="color:${c.textColor};background:${c.bgColor};padding:2px 8px;border-radius:4px;font-size:12px;font-weight:500;">${c.text}</span>`
}

const auditOpen = ref(false)
const auditForm = reactive({
  shopId: null,
  decision: 'PASS',       // PASS | REJECT
  rejectReason: ''        // 审核不通过时必填
})
const auditRules = {
  decision: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  rejectReason: [{
    validator: (rule, value, cb) => {
      if (auditForm.decision === 'REJECT' && (!value || !String(value).trim())) return cb(new Error('请输入拒绝原因'))
      cb()
    }, trigger: 'blur'
  }]
}

function openAudit(row) {
  auditForm.shopId = row.shopId
  // 若当前为审核不通过，则默认展示拒绝态并回显原因
  auditForm.decision = row.shopStatus === 4 ? 'REJECT' : 'PASS'
  auditForm.rejectReason = row.auditRejectReason || ''
  auditOpen.value = true
}

function submitAudit() {
  proxy.$refs.auditRef.validate(valid => {
    if (!valid) return
    const payload = {
      shopId: auditForm.shopId,
      shopStatus: auditForm.decision === 'PASS' ? 1 : 4,                 // 通过=正常营业(1)，拒绝=审核不通过(4)
      auditRejectReason: auditForm.decision === 'REJECT' ? auditForm.rejectReason : null
    }
    updateShop(payload).then(() => {
      proxy.$modal.msgSuccess('审核提交成功')
      auditOpen.value = false
      getList()
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    shopId: null,
    businessName: null,
    shopStatus: null,
    shopOpenTime: null,
    shopCloseTime: null,
    shopAnnouncement: null,
    shopName: null,
    shopTel: null,
    shopAddress: null,
    shopIntroduce: null,
    shopType: null,
    shopAvatar: null,
    shopPhoto: null,
    shopLicense: null,
    shopProfit: null,
    deliveryFee: null,
    roomNo: null
  }
  proxy.resetForm("shopRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.shopId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加已入驻商家"
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  // const _shopId = row.shopId || ids.value
  const shopDetail = await getShop(row.shopId);
  const businessName = row.businessName || '未知联系人';
  form.value = {
    ...shopDetail.data, // 店铺基本信息
    businessName: businessName // 关键：同步联系人姓名到表单
  };
  open.value = true;
  title.value = "修改已入驻商家"
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shopRef"].validate(valid => {
    if (valid) {
      if (form.value.shopId != null) {
        updateShop(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addShop(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _shopIds = row.shopId || ids.value
  proxy.$modal.confirm('是否确认删除已入驻商家编号为"' + _shopIds + '"的数据项？').then(function() {
    return delShop(_shopIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/shop/export', {
    ...queryParams.value
  }, `shop_${new Date().getTime()}.xlsx`)
}

getList()
</script>
